<template>
    <div class="add-friend-container">
      <!-- 左边搜索 -->
      <div class="left-panel">
        <el-input v-model="searchQuery" placeholder="输入好友用户名" clearable @keyup.enter="searchUser" />
        <div class="search-result">
          <template v-if="searching">
            <p>搜索中...</p>
          </template>
          <template v-else-if="userFound">
            <el-card>
              <div class="user-info">
                <img :src="userInfo.avatar" alt="avatar" class="avatar" />
                <div class="text-info">
                  <h4>{{ userInfo.name }}</h4>
                  <el-button type="primary" size="small" @click="addFriend(userInfo.name)">添加好友</el-button>
                </div>
              </div>
            </el-card>
          </template>
          <template v-else-if="searchQuery">
            <el-empty description="用户不存在" />
          </template>
        </div>
      </div>
  
      <!-- 右边申请列表 -->
      <div class="right-panel">
        <h3>好友申请</h3>
        <el-card v-for="request in friendRequests" :key="request.id" class="request-card">
          <div class="request-info">
            <img :src="request.avatar" class="avatar" />
            <span>{{ request.userId }}</span>
            <div class="actions">
              <div v-if="request.status === 0">
                <el-button type="success" size="small" @click="acceptRequest(request.userId)">接受</el-button>
                <el-button type="danger" size="small" @click="rejectRequest(request.userId)">拒绝</el-button>
              </div>
             <div v-else-if="request.status === 1"><span>已接收好友申请</span></div>
             <div v-else-if="request.status === 2"><span>已拒绝该好友申请</span></div>
            </div>
          </div>
        </el-card>
        <el-empty v-if="friendRequests.length === 0" description="暂无申请" />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted,computed } from 'vue'
  import request from'@/axios/index'
  import {useFriendRequestStore} from '@/stores/friendRequest.js'
import { watch } from 'vue';
import {useFriendStore} from '@/stores/friendStore'

  const friendRequestStore  = useFriendRequestStore();
  const searchQuery = ref('')
  const searching = ref(false)
  const userFound = ref(false)
  const userInfo = ref({})
  const friendRequests = computed(()=>friendRequestStore.friendRequest);
  const username = ref()
  const friendStore = useFriendStore()
  
  // 模拟 socket 通信
  const searchUser = () => {
    searching.value = true
    userFound.value = false
    request.get('/user/find/'+searchQuery.value).then((res)=>{
      console.log("res-addFriend: ",res);
      if(res) {
        userInfo.value = {
          id: res.userId,
          name: res.username,
          avatar: 'https://placekitten.com/80/80'
        }
        userFound.value = true;
      }else{
        userFound.value = false;
      }
      searching.value = false
    })
      
     
  }
  
  const addFriend = (userId) => {
    // 发送 add_friend 请求
    console.log('添加好友：', userId)
    request.post('/user/friend/deal',{
      friendName : userId,
      status: 0,
    }).then((res)=>{
      console.log("res-addFriend: ",res);
    })
  }
  
  const acceptRequest = (id) => {
    console.log('接受好友：', id)
    request.post('/user/friend/deal',{
      friendName : id,
      status:1,
    }).then((res)=>{
      console.log("接受好友申请： ",res);
      // friendRequests.value = friendRequests.value.filter(f=> f.userId !== id)
      friendRequestStore.acceptStatus(id);
      friendStore.addFriend({
        senderId: id,
      });
    })
  }
  
  const rejectRequest = (id) => {
    console.log('拒绝好友：', id)
    request.post('/user/friend/deal',{
      friendName: id,
      status: 2,
    }).then((res)=>{
      console.log("拒绝好友申请： ",res);
      friendRequestStore.refuseStatus(id);
    })
  }

  // watch(()=>friendRequestStore.ifUpdate,(newVal)=>{
  //   console.log("是否重新发请求获取好友申请",newVal)
  //   if(newVal == true){
  //       request.get('/friend/newAll').then((res)=>{
  //       friendRequests.value = res;
  //       friendRequestStore.Noupdate();
  //     })
  //   }
  // })
  
  // 初始加载申请列表（模拟）
  onMounted(() => {
    electronAPI.getUsername().then((res)=>{
      username.value = res;
    })

    request.get('/friend/newAll').then((res)=>{
      console.log("最开始好友请求",res);
      const cur = [];
      res.forEach(element => {
        if(element.friendId == username.value){
          cur.push(element);
        }
      });
      friendRequestStore.initRequests(cur);
    })
  })
  </script>
  
  <style scoped>
  .add-friend-container {
    display: flex;
    padding: 20px;
    gap: 20px;
  }
  .left-panel, .right-panel {
    flex: 1;
  }
  .search-result {
    margin-top: 20px;
  }
  .user-info, .request-info {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  .text-info {
    display: flex;
    flex-direction: column;
  }
  .actions {
    margin-left: auto;
    display: flex;
    gap: 10px;
  }
  .request-card {
    margin-bottom: 10px;
  }
  </style>
  